<?
    /**
     * Smarty plugin
     * @package Smarty
     * @subpackage plugins
     * @author Mathaeus Zingerle
     */


    /**
     * Smarty {load_images} function plugin
     *
     * Type:     function
     * Name:     load_images
     * Purpose:  Loads Images of a certain Node / Page
     *   @param array
     *   @param Smarty
     *
     * This smarty plugin can be talked to using the following
     * template parameters:
     *   
     *   * var (string) -- name of variable where to load the 
     *                     data tree to
     *                     >> default: stats
     *
     * @return string
     */
    function smarty_function_load_images($params, &$smarty){
        global $db, $nodeData; // create a link to the database connection

        //pre-process parameters
        //variable name
        if(empty($params['var'])){
            $var = 'files';
        }else{
            $var = $params['var'];
        }

        if(!empty($nodeData['pageref'])){
            $path = ROOT.'files'.DIRECTORY_SEPARATOR.'pages'.DIRECTORY_SEPARATOR.(int)$nodeData['pageref'].DIRECTORY_SEPARATOR;
        }else{
            $path = ROOT.'files'.DIRECTORY_SEPARATOR.'nodes'.DIRECTORY_SEPARATOR.(int)$nodeData['nodeid'].DIRECTORY_SEPARATOR;   
        }
        
        
        //get the file list
        $files = array();
        $tentry = array();

        if(is_dir($path)){
            $d = dir($path);
            while (false !== ($entry = $d->read())){
                if(!is_dir($path.$entry)){
                    
                    $id = $db->getOne("SELECT id FROM added_files WHERE added_files.filename = '".$entry."'");
                    
                    if (!empty($id)) { 
                    
                    $files[] = array(
                                        'name'  =>  $entry,
                                        'size'  =>  ceil(filesize($path.$entry)/1024).' Kb',
                                        'path'	=> 	'files'.DIRECTORY_SEPARATOR.'pages'.DIRECTORY_SEPARATOR.(int)$nodeData['pageref'].DIRECTORY_SEPARATOR,
                                        'id'	=> $id
                                    );
                    }                
                }
            }
            $d->close();
        }
            
        //give all this shit to smarty
        $smarty->assign($var,$files);
    }
?>